package se.rende.schema2ical.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import se.rende.schema2ical.client.PassTime;
import se.rende.schema2ical.client.Schema;

public class GetICalServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * Returns an iCal document for the saved schema.
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userHome = System.getProperty("user.home");
		if (userHome != null) {
			try {
				
				String fileName = "save.json";
				File saveDir = new File(userHome, ".schema2ical");
				File jsonFile = new File(saveDir, fileName);

				Schema schema = new Schema(getFileText(jsonFile));
				
				String iCalText = writeSchemaAsICal(schema);
				
				resp.setContentType("text/calendar");
				resp.setHeader("Content-Disposition", "attachment; filename=" + "save.ics");
				resp.setContentLength(iCalText.length());
				
				PrintWriter pw = resp.getWriter();
				pw.write(iCalText);
				pw.close();
				
				resp.setStatus(200);
			} catch (IOException e) {
				System.err.println(e);
				resp.setStatus(500);
			} catch (ParseException e) {
				System.err.println(e);
				resp.setStatus(500);
			}
		} else {
			System.err.println("system property user.home=" + userHome);
			resp.setStatus(500);
		}
	}

	private String writeSchemaAsICal(Schema schema) throws ParseException {
		StringBuilder sb = new StringBuilder();
		sb.append("BEGIN:VCALENDAR\n"
			 + "VERSION:1.0\n"
			 + "PRODID:Schema2ical rolling schema generator\n");
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat schemaDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		cal.setTime(schemaDateFormat.parse(schema.getStartDate()));
		SimpleDateFormat iCalDateFormat = new SimpleDateFormat("yyyyMMdd");
		int weeksPerCycle = schema.getPassCount() / 7;
		for (int i = 0; i < schema.getPasses().length(); i++) {
			char ch = schema.getPasses().charAt(i);
			PassTime passTime = schema.getPassTime(ch);
			if (passTime != null) {
				sb.append("BEGIN:VEVENT\n"
						+ "SUMMARY:cc\n"
						+ "DTSTART:" + iCalDateFormat.format(cal.getTime()) + "T" + passTime.getFromTimeHHmm() + "00\n"
						+ "DTEND:" + iCalDateFormat.format(cal.getTime()) + "T" + passTime.getToTimeHHmm() + "00\n"
						+ "RRULE:FREQ=WEEKLY;INTERVAL=" + weeksPerCycle + "\n"
						+ "END:VEVENT\n");				
				cal.add(Calendar.DATE, 1);
			} else if (ch == '-') {
				cal.add(Calendar.DATE, 1);
			}
		}
		sb.append("END:VCALENDAR\n");
		return sb.toString();
	}

	/**
	 * Returns utf-8 contents of file as a string.
	 * @param file
	 * @return file contents
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	private String getFileText(File file) throws FileNotFoundException,
			IOException, UnsupportedEncodingException {
		byte[] buf = new byte[(int)file.length()];
		FileInputStream r = new FileInputStream(file);
		r.read(buf);
		r.close();
		String jsonText = new String(buf, "utf-8");
		return jsonText;
	}
}
